classes and objects 1

Class is user defined data type; whereas (int, char, float) are primitive or inbuit data type.

example:

  1. Student vishal;

Here Student is name of user defined data type and vishal is name of variable of such data type.

Code

We will break our code in three files (main.cpp, Student.cpp(contains function and variable definition), Student.hpp(contains function and variable declaration))

1. main.cpp


/******************************************************************************
* File:             classes.cpp
*
* Author:           vishal rao  
* Created:          07/30/24 
*****************************************************************************/
#include "Student.hpp"
int main(int argc, char *argv[])
{
	
	std::cout << "program starts :" << std::endl;
	{ //see what happens if we remove the {}
		/* Student vishal; */
		Student* naresh= new Student;
		naresh->m_name="naresh";
		delete naresh; // without it destructor is not called
	}
	

	Student s1,s2;

	s1.m_name="vishal"; //only work if m_name is public, destructor for first variable is called in end
	s1.printname();

	s2.m_name="naersh";
	s2.printname();

	std::cout << "program ends" << std::endl;
	 

	return 0;
}

2. Student.hpp


#ifndef STUDENT_HPP
#define STUDENT_HPP 

#include <iostream>
class Student{ //curly braces gives skope of class
	
	public:
		std::string m_name;
		Student();//constructor
		~Student();//destructor
		void printname();
	
	
	private: 
		//hidden attributes and variables of class
	
};
#endif /* ifndef STUDENT_HPP */

3. Student.cpp

#include "Student.hpp"

Student::Student(){
	std::cout << "Constructor is called" << std::endl;
}

Student::~Student()
{
	std::cout << "Destructor is called " << std::endl;
}

void Student::printname(){
	std::cout << "name is "<<m_name<< std::endl;
}

output

program starts :
Constructor is called
Destructor is called
Constructor is called
Constructor is called
name is vishal
name is naersh
program ends
Destructor is called
Destructor is called